﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SSPharma.Biz.HeThong;
using SSPharma.Common;
using System.Data;
using SSPharma.View.TimKiem;

namespace SSPharma.View.HeThong
{
    /// <summary>
    /// Interaction logic for frmResponMenu.xaml
    /// </summary>
    public partial class frmResponMenu : Window
    {
       
        #region valible
        //dataset dung de luu  dữ liệu xuống database
        private DataSet dsData;
        //dt delete dữ liệu
        private DataTable dtDeleted;
        // enum dùng để lưu trữ trạng thái mode form
        private UtilityUIElement.FormMode isMode;
        // khai báo đối tượng BizResponseMenu
        private BizResponseMenu _BizResponseMenu;
        //// add a delegate
        public delegate void IdentityValues();
        //// add an event of the delegate type
        public event IdentityValues IdentityValue;
        private string controlName;
        #endregion

        #region contructor
        /// <summary>
        /// contructor tham số chuyền vào là mã Response
        /// </summary>
        /// <param name="Id"></param>
        public frmResponMenu(string Id)
        {
            InitializeComponent();
            _BizResponseMenu = new BizResponseMenu();
            try
            {
                this.BeginMode();
                this.EditMode();
                GetDataMenuTheoMa(Id);
            }
            catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
        }
        /// <summary>
        /// User:TAMNN 21/07/2014
        /// Contructor mac dinh
        /// </summary>
        public frmResponMenu()
        {
            InitializeComponent();
            _BizResponseMenu = new BizResponseMenu();
             
            try
            {
                this.BeginMode();
                this.NewMode();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
        }
        #endregion

        #region Các Hàm Mode form
        /// <summary>
        /// User:TAMNN ; 18/07/2014
        /// Mục đích: chạy khi bắt đầu vào form
        /// </summary>
        private void BeginMode()
        {
            this.EnableControl(false);
            this.GetCauTrucData();
        }
        /// <summary>
        /// User:TAMNN ; 18/07/2014
        /// Mục đích: chạy khi có mã chứng từ
        /// </summary>
        private void EditMode()
        {
            isMode = UtilityUIElement.FormMode.EditMode;
            this.EnableControl(true);
        }
        /// <summary>
        /// User:TAMNN ; 18/07/2014
        /// Mục đích: thêm mới form
        /// </summary>
        private void NewMode()
        {
            this.ResetTemp();
            this.isMode = UtilityUIElement.FormMode.NewMode;
            this.EnableControl(true);
            this.dsData.Tables["dt_ResponseMenu"].Rows.Clear();
            this.dsData.Tables["dt_ResponseMenu"].AcceptChanges();
            this.SetDefaulControl();
        }
        /// <summary>
        ///  User:TAMNN ; 18/07/2014
        ///  Mục đích: save xong dữ liệu thì gọi để đổ lại dữ liệu cho các controll
        /// </summary>
        private void SaveMode()
        {
            isMode = UtilityUIElement.FormMode.EditMode;
            this.EnableControl(true);
            DataTable dt = _BizResponseMenu.ft_GetDataResponseMenuTheoMa(txtMaResponse.Text);// lấy dữ liệu theo mã
            dt.TableName = "dt_ResponseMenu";
            this.dsData.Tables.Remove(this.dsData.Tables["dt_ResponseMenu"]);
            this.dsData.Tables.Add(dt);
        }
        #endregion

        #region Event
        /// <summary>
        /// User:TAMNN; 18/07/2014
        /// Cập nhật dữ liệu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCapNhat_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                string Message = string.Empty;
                Message = this.CheckDataBeforeSave();
                if (!string.IsNullOrEmpty(Message))
                {
                    MessageBox.Show(Message, "SSPharma");
                    return;
                }
                this.GetDataBeforeSave();//lấy dữ liệu trước khi lưu
                _BizResponseMenu.fg_UpdateResponseMenu(dsData.Tables["dt_ResponseMenu"]);
                MessageBox.Show("Lưu thành công !");
                this.SaveMode();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
        }
        /// <summary>
        /// User:TAMNN; 18/07/2014
        /// Nút thoát form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnThoat_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                this.IdentityValue();
                this.Close();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
        }
        /// <summary>
        /// User: TAMNN; 18/07/2014
        /// Thoát form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closed(object sender, System.EventArgs e)
        {
            try
            {
                this.IdentityValue();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
        }
        /// <summary>
        /// User: TAMNN 05/08/2014
        /// Mục đích: checked cột sử dụng
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void g_Menu_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            try
            {
                DataRowView row = (DataRowView)g_Menu.SelectedItems[0];
                int index = g_Menu.CurrentCell.Column.DisplayIndex;
                if (index == 0)
                    row["Choose"] = "True";
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }
        /// <summary>
        /// User: TAMNN 23/07/2014
        /// Mục đích: chọn tất cả
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkCheckAll_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (chkCheckAll.IsChecked == true)
            {
                foreach (DataRow row in dsData.Tables["dt_ResponseMenu"].Rows)
                {
                    row["Choose"] = "True";
                }
            }
            else
            {
                foreach (DataRow row in dsData.Tables["dt_ResponseMenu"].Rows)
                {
                    row["Choose"] = "False";
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtMaResponse_LostFocus(object sender, System.Windows.RoutedEventArgs e)
        {
            //DataTable TableData = _BizResponseMenu.ft_KiemTraResponseTheoMa(txtMaResponse.Text);// lấy dữ liệu theo mã
            //if (TableData.Rows.Count == 0)
            //{
            //    MessageBox.Show("Dữ liệu không hợp lệ", "SSPharma");
            //    dsData.Tables["dt_ResponseMenu"].Clear();
            //    g_Menu.DataContext = dsData.Tables["dt_ResponseMenu"].AsDataView();
            //    return;
            //}
            //else
            //{
            //    txtTenResponse.Text = TableData.Rows[0]["TenResponse"].ToString();
            //    TableData = _BizResponseMenu.ft_GetDataResponseMenuTheoMa(txtMaResponse.Text);
            //    TableData.TableName = "dt_ResponseMenu";
            //    this.dsData.Tables.Remove(this.dsData.Tables["dt_ResponseMenu"]);
            //    this.dsData.Tables.Add(TableData);
            //    g_Menu.DataContext = dsData.Tables["dt_ResponseMenu"].AsDataView();
            //}
            
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtMaResponse_KeyUp(object sender, KeyEventArgs e)
        {
            txtTenResponse.Text = "";
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.F5)
            {
                string p_sStoreName = string.Empty, p_sParams = string.Empty, p_sValues = string.Empty;
                var focusedControl = FocusManager.GetFocusedElement(this);
                Control control = (Control)focusedControl;
                controlName = control.Name;
                if (controlName.Equals("txtMaResponse"))
                {
                    LibraryFunctionFind.StringTimKiemReponse(ref p_sStoreName, ref p_sParams, ref p_sValues);
                    FunctionShowForm(p_sStoreName, p_sParams, p_sValues);
                }
            }
        }
        
        #endregion

        #region Utility function
        /// <summary>
        /// User: TAMNN; 18/07/2014
        /// lấy cấu trúc table trong sql để thực hiện thêm, xóa, sửa dữ liệu
        /// </summary>
        private void GetCauTrucData()
        {
            dsData = _BizResponseMenu.fs_LayCauTrucTable();
            dtDeleted = dsData.Tables["dt_ResponseMenu"].Clone();
        }
        /// <summary>
        /// User: TAMNN; 18/07/2014
        /// lấy dữ liệu trước khi lưu
        /// </summary>
        private void GetDataBeforeSave()
        {
            foreach (DataRow row in dsData.Tables["dt_ResponseMenu"].Rows)
            {
                if (row["Choose"].ToString() == "True" && string.IsNullOrEmpty(row["MaResponse"].ToString()))
                {
                    row["MaResponse"] = txtMaResponse.Text;
                    row["TenResponse"] = txtTenResponse.Text;
                    row["MaMenu"] = row["MaMenuHienThi"];
                    row["TenMenu"] = row["TenMenuHienThi"];
                    row["GhiChu"] = txtGhiChu.Text;
                    row["TinhTrang"] = chkSuDung.IsChecked;
                    row["ModifiedDate"] = LibraryFormatConverter.ConvertStringDDMMYYYYToYYYYMMDD(LibraryFormatConverter.SetStringDateDefault);
                    row["ModifiedBy"] = Global.UserName;
                    row["CreatedDate"] = LibraryFormatConverter.ConvertStringDDMMYYYYToYYYYMMDD(LibraryFormatConverter.SetStringDateDefault);
                    row["CreatedBy"] = Global.UserName;
                    row.AcceptChanges();
                    row.SetAdded();
                }
                else if (row["Choose"].ToString() == "False" && !string.IsNullOrEmpty(row["MaResponse"].ToString()))
                {

                    row.AcceptChanges();
                    dtDeleted.ImportRow(row);
                }
            }
            // Kiểm tra đã xóa những dòng nào
            int num = this.dsData.Tables["dt_ResponseMenu"].Rows.Count - 1;
            for (int i = this.dtDeleted.Rows.Count - 1; i >= 0; i--)
            {
                this.dsData.Tables["dt_ResponseMenu"].ImportRow(this.dtDeleted.Rows[i]);
                num++;
                this.dsData.Tables["dt_ResponseMenu"].Rows[num].AcceptChanges();
                this.dsData.Tables["dt_ResponseMenu"].Rows[num].Delete();
            }

        }
        /// <summary>
        /// User: TAMNN; 18/07/2014
        /// Lấy Menu theo mã Menu
        /// </summary>
        /// <param name="strMa"></param>
        private void GetDataMenuTheoMa(string strMa)
        {
            DataTable TableData = _BizResponseMenu.ft_GetDataResponseMenuTheoMa(strMa);// lấy dữ liệu theo mã
            TableData.TableName = "dt_ResponseMenu";
            this.dsData.Tables.Remove(this.dsData.Tables["dt_ResponseMenu"]);
            this.dsData.Tables.Add(TableData);
            txtTenResponse.Text = TableData.Rows[0]["TenResponse"].ToString();
            chkSuDung.IsChecked = TableData.Rows[0]["TinhTrang"].ToString().Equals("True")?true:false;
            txtMaResponse.Text = strMa;
            g_Menu.DataContext = dsData.Tables["dt_ResponseMenu"].AsDataView();
        }
        /// <summary>
        /// User: TAMNN; 18/07/2014
        /// xóa toàn bộ dữ liệu trên các controll
        /// </summary>
        private void ResetTemp()
        {
            UtilityUIElement.BlankControlText(this.LayoutRoot.Children);
        }
        /// <summary>
        /// User: TAMNN; 18/07/2014
        /// kiểm tra các cột bắt buộc và các cột tính toán đúng hay sai.
        /// </summary>
        /// <returns></returns>
        private string CheckDataBeforeSave()
        {
            string Message = string.Empty;
            if (string.IsNullOrEmpty(txtMaResponse.Text))
            {
                Message = Message + "Nhập mã Response" + "\n";
            }
            if (string.IsNullOrEmpty(txtTenResponse.Text))
            {
                Message = Message + "Nhập tên Response" + "\n";
            }
            if (this.dsData.Tables["dt_ResponseMenu"].Rows.Count == 0)
            {
                Message = Message + "Không có chi tiết" + "\n";
            }
            return Message;
         }
        /// <summary>
        /// User: TAMNN; 18/07/2014
        /// ẩn hiện controll
        /// </summary>
        /// <param name="isEnable"></param>
        private void EnableControl(bool isEnable)
        {
            UtilityUIElement.Enable_Control(isEnable, this.LayoutRoot.Children);
            txtTenResponse.IsEnabled = false;
        }
        /// <summary>
        /// User: TAMNN; 18/07/2014
        /// gán các giá trị mặc định cho các controll
        /// </summary>
        private void SetDefaulControl()
        {
            chkSuDung.IsChecked = true;
        }
        
        #region Hàm dùng cho tìm kiếm form
        private void FunctionShowForm(string p_sStoreName, string p_sParams, string p_sValues)
        {
            var formKeySearch = new frmTimKiem(p_sStoreName, p_sParams, p_sValues);
            formKeySearch.IdentityValue += new frmTimKiem.IdentityValues(Search_Form);
            formKeySearch.ShowDialog();
        }
        /// <summary>
        /// User: TAMNN 11/08/2014
        /// Mục đích: lấy dữ liệu trả về của form search
        /// </summary>
        /// <param name="keyReturn"></param>
        private void Search_Form(string keyReturn)
        {
            string str = keyReturn;
            switch (controlName)
            {
                case "txtMaResponse":
                    txtMaResponse.Text = str;
                    DataTable TableData = _BizResponseMenu.ft_KiemTraResponseTheoMa(txtMaResponse.Text);// lấy dữ liệu theo mã
                    if (TableData.Rows.Count == 0)
                    {
                        MessageBox.Show("Dữ liệu không hợp lệ", "SSPharma");
                        dsData.Tables["dt_ResponseMenu"].Clear();
                        g_Menu.DataContext = dsData.Tables["dt_ResponseMenu"].AsDataView();
                        return;
                    }
                    else
                    {
                        txtTenResponse.Text = TableData.Rows[0]["TenResponse"].ToString();
                        TableData = _BizResponseMenu.ft_GetDataResponseMenuTheoMa(txtMaResponse.Text);
                        TableData.TableName = "dt_ResponseMenu";
                        this.dsData.Tables.Remove(this.dsData.Tables["dt_ResponseMenu"]);
                        this.dsData.Tables.Add(TableData);
                        g_Menu.DataContext = dsData.Tables["dt_ResponseMenu"].AsDataView();
                    }
                    break;

            }
        }
        #endregion

        #endregion

        #region Tính toán
        
        #endregion

    }
}
